package com.weir.oauth2.authority.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.weir.commons.utils.BaseUtil;
import com.weir.oauth2.authority.entity.OauthClientDetails;
import com.weir.oauth2.authority.mapper.OauthClientDetailsMapper;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

//@Service
public class UserDetailsServiceImpl implements UserDetailsService {

	private static final Logger LOGGER = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
	@Autowired
	private OauthClientDetailsMapper oauthClientDetailsMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		LOGGER.info("UserDetailsServiceImpl-----------");
		OauthClientDetails clientDetails = oauthClientDetailsMapper
				.selectOne(new QueryWrapper<OauthClientDetails>().eq("client_id", username.trim()));
		Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
		boolean enabled = true; // 可用性 :true:可用 false:不可用
		boolean accountNonExpired = true; // 过期性 :true:没过期 false:过期
		boolean credentialsNonExpired = true; // 有效性 :true:凭证有效 false:凭证无效
		boolean accountNonLocked = true; // 锁定性 :true:未锁定 false:已锁定

		if (StringUtils.isNotBlank(clientDetails.getAuthorities())) {
			List<String> list = BaseUtil.commaDelimitedToStringList(clientDetails.getAuthorities());
			if (BaseUtil.isEmptyList(list)) {
				for (String s : list) {
					// 角色必须是ROLE_开头
					SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(s);
					grantedAuthorities.add(grantedAuthority);
				}
			}
		}
		User user = new User(clientDetails.getClientId(), clientDetails.getClientSecret(), enabled, accountNonExpired,
				credentialsNonExpired, accountNonLocked, grantedAuthorities);
		return user;
	}
}
